<template>
	<div class="container">
		<div class="header">
			<h3 class="panel-title">材料管理</h3>
			<div class="header-right">
				<el-button
					@click="saveAllMaterials"
					type="success"
					size="large"
					class="save-all-btn"
				>
					<i class="el-icon-check"></i> 一键保存所有
				</el-button>
				<el-button @click="addMaterial" type="primary" size="large" class="add-btn">
					<i class="el-icon-plus"></i> 添加材料
				</el-button>
			</div>
		</div>
		<div class="material-list">
			<div class="material-item" v-for="item in materialArrs" :key="item.title">
				<el-button
					size="large"
					@click="handleMaterItem(item)"
					:type="currentIndex == item.id ? 'primary' : 'default'"
					:class="['material-item-title', currentIndex == item.id ? 'active' : '']"
				>
					{{ item.title }}
				</el-button>
			</div>
		</div>
		<div class="content-area">
			<div class="editor-container">
				<wang
					height="400px"
					@change="editorChange"
					:key="currentMaterial.id + '_content'"
					v-model="currentMaterial.content"
				/>
			</div>
		</div>
		<!-- 将按钮放在真正的最底部 -->
		<div class="bottom-buttons">
			<el-button @click="handleSaveMaterial" class="save-btn" type="primary" size="large">
				<i class="el-icon-check"></i> 保存材料{{
					currentMaterial.title ? currentMaterial.title.replace('材料', '') : ''
				}}
			</el-button>
			<!-- 删除按钮 -->
			<el-button class="delete-btn" type="danger" size="large" @click="deleteMaterial">
				<i class="el-icon-delete"></i> 删除材料{{
					currentMaterial.title ? currentMaterial.title.replace('材料', '') : ''
				}}
			</el-button>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { shenlunDetail, addSlcl, deleteSlcl } from '../../api/slxx';
import { ref, onMounted, watch } from 'vue';
const props = defineProps({
	id: {
		type: String,
		default: ''
	}
});
const isEdit = ref(true);

let currentMaterial = ref<any>({
	content: ''
});
let currentIndex = ref(0);
const materialArrs = ref<any>([]);
const handleMaterItem = async item => {
	// 如果当前正在编辑的材料与要切换的材料相同，不做任何操作
	if (currentIndex.value === item.id) return;

	try {
		// 先保存当前正在编辑的材料
		if (currentMaterial.value.id && currentMaterial.value.content) {
			await saveMaterial();
		}

		// 深拷贝避免直接修改列表中的对象
		currentMaterial.value = JSON.parse(JSON.stringify(item));
		currentIndex.value = item.id;
		// 设置为编辑模式
		isEdit.value = true;
	} catch (error) {
		console.error('切换材料时出错:', error);
		ElMessage.error('保存当前材料失败，请手动保存后再切换');
	}
};

const addMaterial = async () => {
	try {
		// 先保存当前正在编辑的材料
		if (currentMaterial.value.id && currentMaterial.value.content) {
			await saveMaterial();
		}

		isEdit.value = false;
		let obj = {
			id: new Date().getTime(), // 临时ID，保存时会被删除
			content: '',
			title: '材料' + (materialArrs.value.length + 1)
		};
		// 先清除当前选中状态
		currentIndex.value = obj.id;
		currentMaterial.value = JSON.parse(JSON.stringify(obj));
		// 添加到列表中，但不立即保存到后端
		materialArrs.value = [...materialArrs.value, obj];
	} catch (error) {
		console.error('添加新材料时出错:', error);
		ElMessage.error('保存当前材料失败，请手动保存后再添加');
	}
};

// 处理点击保存按钮事件
const handleSaveMaterial = (evt: MouseEvent) => {
	saveMaterial();
};

// 保存材料
const saveMaterial = async () => {
	console.log(currentMaterial.value);
	if (!isEdit.value) {
		delete currentMaterial.value.id;
	}

	const res = await addSlcl({
		shenlunId: props.id,
		// content: currentMaterial.value.content,
		...currentMaterial.value
	});
	if (res.code === 200) {
		// ElMessage.success(isEdit.value ? '更新成功' : '新增成功');
		// 保存成功后重新获取材料列表，但保持当前选中的材料ID
		const currentId = currentMaterial.value.id;
		await init2();
		// 如果是编辑模式，尝试重新选中之前选中的材料
		if (isEdit.value && currentId) {
			const currentItem = materialArrs.value.find(item => item.id === currentId);
			if (currentItem) {
				currentMaterial.value = JSON.parse(JSON.stringify(currentItem));
				currentIndex.value = currentId;
			}
		}
	}
};

// 一键保存所有材料
const saveAllMaterials = async () => {
	try {
		// 先保存当前正在编辑的材料
		const currentId = currentMaterial.value.id;

		// 保存当前编辑的材料
		await saveMaterial();

		// 显示保存进度
		ElMessage.info('正在保存所有材料...');

		// 获取最新的材料列表
		const res = await shenlunDetail(props.id);
		if (res.data && res.data.cailiaoList) {
			// 保存所有材料
			const savePromises = res.data.cailiaoList.map(async item => {
				// 跳过当前已保存的材料
				if (item.id === currentId) return;

				// 保存每个材料
				await addSlcl({
					shenlunId: props.id,
					...item
				});
			});

			// 等待所有保存操作完成
			await Promise.all(savePromises);

			// 重新加载材料列表，但保持当前选中的材料
			await init2();

			// 尝试重新选中之前选中的材料
			if (currentId) {
				const currentItem = materialArrs.value.find(item => item.id === currentId);
				if (currentItem) {
					currentMaterial.value = JSON.parse(JSON.stringify(currentItem));
					currentIndex.value = currentId;
				}
			}

			// 显示保存成功消息
			ElMessage.success('所有材料保存成功');
		}
	} catch (error) {
		console.error('保存所有材料时出错:', error);
		ElMessage.error('保存失败，请重试');
	}
};

const deleteMaterial = async () => {
	const res = await deleteSlcl(currentMaterial.value.id);
	if (res.code === 200) {
		ElMessage.success('删除成功');
		init2();
	}
};
const editorChange = val => {
	currentMaterial.value.content = val;
};
const init2 = async () => {
	const res = await shenlunDetail(props.id);
	if (res.data && res.data.cailiaoList) {
		// 保存当前选中的材料ID
		const currentId = currentIndex.value;

		// 更新材料标题
		res.data.cailiaoList.forEach((item, index) => {
			item.title = '材料' + Number(index + 1);
		});

		// 更新材料列表
		materialArrs.value = [...res.data.cailiaoList];

		if (materialArrs.value.length > 0) {
			if (isEdit.value) {
				// 尝试找回之前选中的材料
				const currentItem = materialArrs.value.find(item => item.id === currentId);
				if (currentItem) {
					currentMaterial.value = JSON.parse(JSON.stringify(currentItem));
					currentIndex.value = currentId;
				} else {
					// 如果找不到之前选中的材料，选择最后一个
					currentIndex.value = materialArrs.value.at(-1)?.id || 0;
					currentMaterial.value = JSON.parse(
						JSON.stringify(materialArrs.value.at(-1) || { content: '' })
					);
				}
			} else {
				// 非编辑模式，选择最后一个材料
				currentIndex.value = materialArrs.value.at(-1)?.id || 0;
				currentMaterial.value = JSON.parse(
					JSON.stringify(materialArrs.value.at(-1) || { content: '' })
				);
				isEdit.value = true;
			}
		} else {
			currentMaterial.value = { content: '' };
			currentIndex.value = 0;
		}
	}
};
const init1 = async () => {
	const res = await shenlunDetail(props.id);
	if (res.data && res.data.cailiaoList) {
		res.data.cailiaoList.forEach((item, index) => {
			item.title = '材料' + Number(index + 1);
		});
		materialArrs.value = [...res.data.cailiaoList];

		if (materialArrs.value.length > 0) {
			currentIndex.value = materialArrs.value[0]?.id || 0;
			currentMaterial.value = JSON.parse(
				JSON.stringify(materialArrs.value[0] || { content: '' })
			);
		} else {
			currentMaterial.value = { content: '' };
			currentIndex.value = 0;
		}
	}
};
watch(
	() => props.id,
	newVal => {
		if (newVal) {
			// 重置状态
			currentMaterial.value = {
				content: ''
			};
			currentIndex.value = 0;
			materialArrs.value = [];

			setTimeout(() => {
				init1();
			}, 200);
		}
		console.log(props.id);
	},
	{ immediate: true }
);

onMounted(() => {
	// init1();
});
</script>
<style lang="scss" scoped>
.container {
	display: flex;
	flex-direction: column;
	height: 100%;
	position: relative;
	padding: 16px;
	box-sizing: border-box;
}

.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
	padding-bottom: 12px;
	border-bottom: 1px solid #ebeef5;

	.header-right {
		display: flex;
		align-items: center;
		gap: 16px;
	}
}

.panel-title {
	margin: 0;
	font-size: 18px;
	font-weight: 600;
	color: #303133;
}

.add-btn {
	background-color: #409eff;
	border-color: #409eff;

	&:hover,
	&:focus {
		background-color: #66b1ff;
		border-color: #66b1ff;
	}
}

.content-area {
	flex: 1;
	overflow-y: auto;
	padding-bottom: 120px; /* 为底部按钮留出空间 */
}

.editor-container {
	background-color: #fff;
	border-radius: 4px;
	border: 1px solid #ebeef5;
	padding: 8px;
	margin-top: 16px;
}

.material-list {
	margin-bottom: 16px;
	display: flex;
	overflow-x: auto;
	padding: 4px 0;
	scrollbar-width: thin;

	&::-webkit-scrollbar {
		height: 6px;
	}

	&::-webkit-scrollbar-thumb {
		background-color: #c0c4cc;
		border-radius: 3px;
	}

	.material-item {
		margin-right: 10px;

		.material-item-title {
			border-radius: 4px;
			transition: all 0.3s;

			&.active {
				transform: translateY(-2px);
				box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
			}
		}
	}
}

.bottom-buttons {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 16px;
	box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
	display: flex;
	gap: 16px;

	.save-btn,
	.delete-btn {
		flex: 1;
		transition: all 0.3s;

		&:hover {
			transform: translateY(-2px);
		}
	}

	.save-btn {
		background-color: #67c23a;
		border-color: #67c23a;

		&:hover,
		&:focus {
			background-color: #85ce61;
			border-color: #85ce61;
		}
	}

	.delete-btn {
		background-color: #f56c6c;
		border-color: #f56c6c;

		&:hover,
		&:focus {
			background-color: #f78989;
			border-color: #f78989;
		}
	}
}

.save-all-btn {
	background-color: #67c23a;
	border-color: #67c23a;

	&:hover,
	&:focus {
		background-color: #85ce61;
		border-color: #85ce61;
	}
}
</style>
